package com.fanshilz.flower2025.business.flower.wechatUser.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import com.fanshilz.flower2025.apps.wechatminiapp.satoken.StpWechatUtil;
import com.fanshilz.flower2025.apps.wechatminiapp.satoken.WechatCurrentUser;
import com.fanshilz.flower2025.apps.wechatminiapp.wechatUser.req.JsCodeLoginReq;
import com.fanshilz.flower2025.business.flower.userIdentity.entity.UserIdentity;
import com.fanshilz.flower2025.business.flower.userIdentity.entity.UserIdentityStatusEnum;
import com.fanshilz.flower2025.business.flower.userIdentity.service.IUserIdentityService;
import com.fanshilz.flower2025.business.flower.wechatUser.entity.UserCheckStatusEnum;
import com.fanshilz.flower2025.framework.resp.Resp;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.fanshilz.flower2025.business.flower.wechatUser.entity.WechatUser;
import com.fanshilz.flower2025.business.flower.wechatUser.mapper.WechatUserMapper;
import com.fanshilz.flower2025.business.flower.wechatUser.service.IWechatUserService;
import io.github.linpeilie.Converter;
import jakarta.annotation.Resource;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

import static com.fanshilz.flower2025.business.flower.userIdentity.entity.table.UserIdentityTableDef.USER_IDENTITY;
import static com.fanshilz.flower2025.business.flower.wechatUser.entity.table.WechatUserTableDef.WECHAT_USER;

/**
 * 服务层实现。
 *
 * @author fugui
 * @since 2024-10-19
 */
@Service
public class WechatUserServiceImpl extends ServiceImpl<WechatUserMapper, WechatUser> implements IWechatUserService {

    @Resource
    private WxMaService wxMaService;
    @Resource
    private IUserIdentityService userIdentityService;
    @Resource
    private Converter converter;

    @Override
    public synchronized Resp<Void> login(JsCodeLoginReq req) {
        try {
            WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(req.getJsCode());
            WechatUser user = getOne(QueryWrapper.create()
                    .where(WECHAT_USER.USER_OPENID.eq(result.getOpenid())));
            if (ObjUtil.isNull(user)) {
                String userNickName = "繁市" + RandomUtil.randomNumbers(6);
                user = WechatUser.builder()
                        .userUuid("1" + RandomUtil.randomNumbers(7))
                        .userOpenid(result.getOpenid())
                        .userUnionid(result.getUnionid())
                        .userNickName(userNickName)
                        .createUserName(userNickName)
                        .createUserId(0L)
                        .build();
                save(user);
            }

            WechatCurrentUser currentUser = converter.convert(user, WechatCurrentUser.class);

            if (UserCheckStatusEnum.TRUE.equals(user.getUserCheckStatus())) {
                UserIdentity ui = userIdentityService.getOne(QueryWrapper.create()
                        .where(USER_IDENTITY.CREATE_USER_ID.eq(user.getUserId()))
                        .where(USER_IDENTITY.IDENTITY_SWITCH.eq(true))
                        .where(USER_IDENTITY.IDENTITY_STATUS_VALUE.eq(UserIdentityStatusEnum.PASS.getValue())));
                currentUser.setIdentityRealName(ui.getIdentityRealName());
                currentUser.setIdentityCompanyName(ui.getIdentityCompanyName());
                currentUser.setIdentityTypeValue(ui.getIdentityTypeValue());
                currentUser.setIdentityTypeLabel(ui.getIdentityTypeLabel());
            }

            currentUser.setSessionKey(result.getSessionKey());
            StpWechatUtil.login(currentUser);

        } catch (WxErrorException e) {
            return Resp.error(ExceptionUtil.getMessage(e));
        }

        return Resp.success();
    }

}
